package fr.ece.ing4.si.stopwatch;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class StopWatch extends JFrame implements ActionListener
{
	private boolean running, resume, reset;
	private static final long serialVersionUID = -8703843689450789725L;
	JButton startStopButton;
	JButton resetButton;
	JLabel timeLabel;

	@Override
	protected void frameInit()
	{
		super.frameInit();
		getContentPane().setLayout(new FlowLayout());
		startStopButton = new JButton();
		resetButton = new JButton();
		timeLabel = new JLabel();
		startStopButton.setText("Start");
		resetButton.setText("Reset");
		timeLabel.setText("0");

		Thread counter = new Thread(new Counter());
		counter.start();

		getContentPane().add(startStopButton);
		getContentPane().add(resetButton);
		getContentPane().add(timeLabel);

		startStopButton.addActionListener(this);
		resetButton.addActionListener(this);
	}

	public void actionPerformed(final ActionEvent event)
	{
		if(event.getSource() == resetButton)
		{
			if(false == running)
			{
				reset = true;
			}
		}
		else
		{
			if(running)
			{
				running = false;
			}
			else
			{
				running = true;
				resume = true;
			}
		}
	}


	public class Counter extends Thread
	{
		public void run()
		{
			while(true)
			{
				if(running)
					startCounting();
				else
					stopCounting();
					resetCounting();
			}
		}

		private void startCounting()
		{
			if(false == resume)
			{
				for(int count = 0; running; count++)
				{
					startStopButton.setText("Stop");
					timeLabel.setText(String.format("%d", count));

					try
					{
						Thread.sleep(1000);
					} catch (InterruptedException ex)
					{
						throw new RuntimeException(ex);
					}
				}
			}
			else
			{
				for(int count = Integer.parseInt(timeLabel.getText()); running; count++)
				{
					startStopButton.setText("Stop");
					timeLabel.setText(String.format("%d", count));

					try
					{
						Thread.sleep(1000);
					} catch (InterruptedException ex)
					{
						throw new RuntimeException(ex);
					}
				}
			}

		}

		private void stopCounting()
		{
			if("0" != timeLabel.getText())
				startStopButton.setText("Resume");

			try
			{
				Thread.sleep(1000);
			} catch (InterruptedException ex)
			{
				throw new RuntimeException(ex);
			}
		}

		private void resetCounting()
		{
			if(reset)
			{
				timeLabel.setText("0");

				startStopButton.setText("Start");

				reset = false;
				resume = false;
			}
		}
	}
}


//private class Counter implements Runnable
//{
//	public void run()
//	{
//		while(true)
//		{
//			if (running)
//				startCounting();
//			else
//				stopCounting();
//		}
//	}
//}
